package com.eeepay.eeepay_v2.api;

import android.app.Activity;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.eeepay.eeepay_v2.util.AllUtils;
import com.eeepay.eeepay_v2.util.AppUpdateUtil;
import com.eeepay.eeepay_v2.util.ConfigPorperties;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.GrpcUtils;
import com.eeepay.v2_library.log.LogUtils;

import java.util.concurrent.TimeUnit;

import cn.eeepay.api.grpc.nano.LoginApiServiceGrpc;
import cn.eeepay.api.grpc.nano.LoginProto;
import io.grpc.ManagedChannel;

/**
 * 描述：根据产品提出的需求；检查APP 版本升级信息 逻辑需修改； 因此在这里我做了二次的封装
 * 作者：zhuangzeqin
 * 时间: 2017/11/2-15:05
 * 邮箱：zzq@eeepay.cn
 */
public class CheckVersionRequestBuilder {
    private final String TAG = "CheckVersionRequestBuilder";
    private boolean isManualCheck = false; //是否手动检查;默认为false
    private Activity mActivity;//上下文对象
    private ResultCallBack resultCallBack;//设置监听接口

    /**
     * 私有的构造函数
     *
     * @param activity
     */
    private CheckVersionRequestBuilder(@NonNull Activity activity) {
        this.mActivity = activity;
    }

    public static CheckVersionRequestBuilder with(@NonNull Activity activity) {
        return new CheckVersionRequestBuilder(activity);
    }

    /**
     * 设置监听接口
     *
     * @param resultCallBack
     * @return
     */
    public CheckVersionRequestBuilder setResultCallBack(@NonNull ResultCallBack resultCallBack) {
        this.resultCallBack = resultCallBack;
        return this;
    }

    /**
     * 是否手动检查
     *
     * @param isManualCheck
     * @return
     */
    public CheckVersionRequestBuilder setManualCheck(boolean isManualCheck) {
        this.isManualCheck = isManualCheck;
        return this;
    }

    /**
     * 开始检查版本信息
     */
    public void startCheckVersion() {
        if (resultCallBack == null) {
            throw new RuntimeException("ResultCallBack is null,you can must implement.");
        }
        GrpcUtils.getInstance().doGrpcTask(Constant.URL.URL, Constant.URL.PORT
                , 0, new GrpcUtils.AsyncTaskListener() {
                    @Override
                    public Object doInBack(ManagedChannel channel, int taskId) {
                        LoginApiServiceGrpc.LoginApiServiceBlockingStub stub = LoginApiServiceGrpc
                                .newBlockingStub(channel)
                                .withDeadlineAfter(Constant.grpc_time_out, TimeUnit.SECONDS);
                        LoginProto.CheckVersionReq req = new LoginProto.CheckVersionReq();
                        req.appNo = ConfigPorperties.getInstance().getAppNo();//APP no
                        req.platform = "0";//平台
                        req.version = ConfigPorperties.getInstance().getVersionName();
                        LogUtils.d("versionName = " + req.version);
                        LoginProto.CheckVersionRes res = stub.checkVersion(req);
                        return res;
                    }

                    @Override
                    public void updateUI(Object result, int taskId) {
                        if (result == null) {
                            resultCallBack.onMessage("网络错误");
                            return;
                        }
                        LoginProto.CheckVersionRes res = (LoginProto.CheckVersionRes) result;
                        if (!res.resMsg.status) {
                            resultCallBack.onMessage(res.resMsg.msg);
                            return;
                        }
                        AppUpdateUtil.downFlag = res.version.downFlag;//1选择更新，2强制更新
                        AppUpdateUtil.downloadUrl = res.version.appUrl;
                        AppUpdateUtil.verDesc = res.version.verDesc;//更新内容描述
                        String str_version = res.version.version;//版本号
                        boolean isForce = TextUtils.equals(AppUpdateUtil.downFlag, "2");
                        if (isForce)//如果是强制升级的情况
                        {
                            AppUpdateUtil.doNewVersionUpdate(mActivity);//直接弹框升级
                        } else {
                            if (isManualCheck)//如果是手动检查；并且无需更新的时候；给出提示
                            {
                                try {
                                    if (AllUtils.compareVersion(str_version, ConfigPorperties.getInstance().getVersionName()) > 0)//需要升级
                                    {
                                        AppUpdateUtil.doNewVersionUpdate(mActivity);//直接弹框升级
                                        resultCallBack.onForce(false);
                                    } else {
                                        resultCallBack.onMessage("已是最新版本");
                                    }
                                } catch (Exception e) {
                                    resultCallBack.onMessage("已是最新版本");
                                    e.printStackTrace();
                                }
                            } else {
                                resultCallBack.onForce(false);//不是强制升级； 并且不是手动检查的话；ps 直接跳过；自动登录到主界面
                            }
                        }

                    }
                });
    }

    /**
     * 提供外围接口；通过接口回传
     */
    public interface ResultCallBack {
        void onMessage(String msg);//失败返回；提示语

        void onForce(boolean isForce);//是否强制升级
    }
}
